package exerise;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 */
public class Ex14 {

    public static void main(String[] args) {
        Ex14 ex14 = new Ex14();
        String[] src = {"flower", "aflow", "flight"};
        String result = ex14.longestCommonPrefix(src);
        System.out.println(result);
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        String temp = strs[0];
        StringBuilder commonPrefix = new StringBuilder(temp);
        for (int i = 1; i < strs.length; i++) {
            String str = strs[i];
            int idx = 0;
            commonPrefix.setLength(0);
            int len = Math.min(temp.length(), str.length());
            while (idx < len) {
                if (temp.charAt(idx) == str.charAt(idx)) {
                    commonPrefix.append(temp.charAt(idx));
                    idx++;
                } else {
                    break;
                }
            }
            temp = commonPrefix.toString();
            if (temp.length() == 0) return "";
        }
        return commonPrefix.toString();
    }
}
